/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Persistencia;

import Logica.Cliente;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Logica.Turno;
import Logica.Vehiculo;
import Persistencia.exceptions.NonexistentEntityException;
import Persistencia.exceptions.PreexistingEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Pablo
 */
public class ClienteJpaController implements Serializable {
    
    public ClienteJpaController(){
        emf = Persistence.createEntityManagerFactory("TpFinalPU");
    }

    public ClienteJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Cliente cliente) throws PreexistingEntityException, Exception {
        if (cliente.getVehiculos() == null) {
            cliente.setVehiculos(new ArrayList<Vehiculo>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Turno unTurno = cliente.getUnTurno();
            if (unTurno != null) {
                unTurno = em.getReference(unTurno.getClass(), unTurno.getNroTurno());
                cliente.setUnTurno(unTurno);
            }
            List<Vehiculo> attachedVehiculos = new ArrayList<Vehiculo>();
            for (Vehiculo vehiculosVehiculoToAttach : cliente.getVehiculos()) {
                vehiculosVehiculoToAttach = em.getReference(vehiculosVehiculoToAttach.getClass(), vehiculosVehiculoToAttach.getNroChasis());
                attachedVehiculos.add(vehiculosVehiculoToAttach);
            }
            cliente.setVehiculos(attachedVehiculos);
            em.persist(cliente);
            if (unTurno != null) {
                Cliente oldUnClienteOfUnTurno = unTurno.getUnCliente();
                if (oldUnClienteOfUnTurno != null) {
                    oldUnClienteOfUnTurno.setUnTurno(null);
                    oldUnClienteOfUnTurno = em.merge(oldUnClienteOfUnTurno);
                }
                unTurno.setUnCliente(cliente);
                unTurno = em.merge(unTurno);
            }
            for (Vehiculo vehiculosVehiculo : cliente.getVehiculos()) {
                Cliente oldUnClienteOfVehiculosVehiculo = vehiculosVehiculo.getUnCliente();
                vehiculosVehiculo.setUnCliente(cliente);
                vehiculosVehiculo = em.merge(vehiculosVehiculo);
                if (oldUnClienteOfVehiculosVehiculo != null) {
                    oldUnClienteOfVehiculosVehiculo.getVehiculos().remove(vehiculosVehiculo);
                    oldUnClienteOfVehiculosVehiculo = em.merge(oldUnClienteOfVehiculosVehiculo);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCliente(cliente.getNroDoc()) != null) {
                throw new PreexistingEntityException("Cliente " + cliente + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Cliente cliente) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente persistentCliente = em.find(Cliente.class, cliente.getNroDoc());
            Turno unTurnoOld = persistentCliente.getUnTurno();
            Turno unTurnoNew = cliente.getUnTurno();
            List<Vehiculo> vehiculosOld = persistentCliente.getVehiculos();
            List<Vehiculo> vehiculosNew = cliente.getVehiculos();
            if (unTurnoNew != null) {
                unTurnoNew = em.getReference(unTurnoNew.getClass(), unTurnoNew.getNroTurno());
                cliente.setUnTurno(unTurnoNew);
            }
            List<Vehiculo> attachedVehiculosNew = new ArrayList<Vehiculo>();
            for (Vehiculo vehiculosNewVehiculoToAttach : vehiculosNew) {
                vehiculosNewVehiculoToAttach = em.getReference(vehiculosNewVehiculoToAttach.getClass(), vehiculosNewVehiculoToAttach.getNroChasis());
                attachedVehiculosNew.add(vehiculosNewVehiculoToAttach);
            }
            vehiculosNew = attachedVehiculosNew;
            cliente.setVehiculos(vehiculosNew);
            cliente = em.merge(cliente);
            if (unTurnoOld != null && !unTurnoOld.equals(unTurnoNew)) {
                unTurnoOld.setUnCliente(null);
                unTurnoOld = em.merge(unTurnoOld);
            }
            if (unTurnoNew != null && !unTurnoNew.equals(unTurnoOld)) {
                Cliente oldUnClienteOfUnTurno = unTurnoNew.getUnCliente();
                if (oldUnClienteOfUnTurno != null) {
                    oldUnClienteOfUnTurno.setUnTurno(null);
                    oldUnClienteOfUnTurno = em.merge(oldUnClienteOfUnTurno);
                }
                unTurnoNew.setUnCliente(cliente);
                unTurnoNew = em.merge(unTurnoNew);
            }
            for (Vehiculo vehiculosOldVehiculo : vehiculosOld) {
                if (!vehiculosNew.contains(vehiculosOldVehiculo)) {
                    vehiculosOldVehiculo.setUnCliente(null);
                    vehiculosOldVehiculo = em.merge(vehiculosOldVehiculo);
                }
            }
            for (Vehiculo vehiculosNewVehiculo : vehiculosNew) {
                if (!vehiculosOld.contains(vehiculosNewVehiculo)) {
                    Cliente oldUnClienteOfVehiculosNewVehiculo = vehiculosNewVehiculo.getUnCliente();
                    vehiculosNewVehiculo.setUnCliente(cliente);
                    vehiculosNewVehiculo = em.merge(vehiculosNewVehiculo);
                    if (oldUnClienteOfVehiculosNewVehiculo != null && !oldUnClienteOfVehiculosNewVehiculo.equals(cliente)) {
                        oldUnClienteOfVehiculosNewVehiculo.getVehiculos().remove(vehiculosNewVehiculo);
                        oldUnClienteOfVehiculosNewVehiculo = em.merge(oldUnClienteOfVehiculosNewVehiculo);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                double id = cliente.getNroDoc();
                if (findCliente(id) == null) {
                    throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(double id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente cliente;
            try {
                cliente = em.getReference(Cliente.class, id);
                cliente.getNroDoc();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.", enfe);
            }
            Turno unTurno = cliente.getUnTurno();
            if (unTurno != null) {
                unTurno.setUnCliente(null);
                unTurno = em.merge(unTurno);
            }
            List<Vehiculo> vehiculos = cliente.getVehiculos();
            for (Vehiculo vehiculosVehiculo : vehiculos) {
                vehiculosVehiculo.setUnCliente(null);
                vehiculosVehiculo = em.merge(vehiculosVehiculo);
            }
            em.remove(cliente);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Cliente> findClienteEntities() {
        return findClienteEntities(true, -1, -1);
    }

    public List<Cliente> findClienteEntities(int maxResults, int firstResult) {
        return findClienteEntities(false, maxResults, firstResult);
    }

    private List<Cliente> findClienteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Cliente.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Cliente findCliente(double id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Cliente.class, id);
        } finally {
            em.close();
        }
    }

    public int getClienteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Cliente> rt = cq.from(Cliente.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
